const app = getApp();
const utils = require('../../utils/utils.js');
let flag = 1;
Page({
    data: {
        userInfo: {},
        info: {},
        isClick: true,
        checkNum: 0,
        used_id: null,
        isfree: 1,
        check_timer: "", // 定时器
        need_tel: 0,
        refuse_show: 0,
        refuse_msg: "",
        refuse_after_borrow: 0,
        need_tel_tip_1: "",
        need_tel_tip_2: "",
        adImg: "",
        isShow: 0
    },
    onLoad: function (options) {
        let openid = app.globalData.openID;
        if (openid != 'miand') {
            // 获取用户信息
            this.userIsAuth();
            // this.getUserInfo();
        } else {
            wx.showModal({
                title: '温馨提示',
                content: 'Hi~请确认登录，登录即可享受充电服务',
                success: function (sm) {
                    if (sm.confirm) {
                        // 未授权，跳转到授权页面
                        wx.navigateTo({
                            url: '../authorization/authorization?scene=2'
                        });
                    } else if (sm.cancel) {
                        wx.showToast({
                            title: "您点击了取消",
                            icon: 'none',
                            duration: 2000
                        });
                    }
                }
            })
        }
        wx.showLoading({
            title: 'loading...',
            mask: true
        });
        // 将传输过来的信息保存起来
        var jsonParse = JSON.parse(options.data);
        this.setData({
            info: jsonParse,
            need_tel: jsonParse.need_tel,
            refuse_show: jsonParse.refuse_show,
            refuse_msg: jsonParse.refuse_msg,
            refuse_after_borrow: jsonParse.refuse_after_borrow,
            need_tel_tip_1: jsonParse.need_tel_tip_1,
            need_tel_tip_2: jsonParse.need_tel_tip_2,
            adImg: jsonParse.adImg,
            isShow: jsonParse.isShow,
        });
        wx.hideLoading();
    },
    // ===================== 判断用户是否授权 =============================
    userIsAuth() {
        let that = this;
        wx.showLoading({
            title: 'loading...',
            mask: true
        });
        utils.httpRequest('/checkAuth', {}, function (res) {
            wx.hideLoading();
            if (res.code == 1) {
                if (res.data.is_auth == 1) { //已授权
                    that.getUserInfo();
                } else {
                    // 未获取到用户昵称信息，需要让用户再次授权
                    wx.navigateTo({
                        url: '../authorization/authorization?scene=2'
                    });
                }
            }
        })
    },
    // =============== 获取用户信息 ====================
    getUserInfo() {
        wx.showLoading({
            title: 'loading...',
            mask: true
        });
        let that = this;
        utils.httpRequest('/getInfo', {}, function (res) {
            wx.hideLoading();
            if (res.code == 1) {
                that.setData({
                    userInfo: res.data.user
                })
            }
        })
    },
    onShow: function (options) {
        this.setData({
            isClick: true
        });
        var pages = getCurrentPages();
        var currPage = pages[pages.length - 1]; //当前页面
        let json = currPage.data;
        if (json.scene == 2) {
            let openid = app.globalData.openID;
            if (openid != 'miand') {
                // 获取用户信息
                this.getUserInfo();
            }
        } else {
            flag = this.data.info.freeDeposit;
            if (flag == 1) {
                flag = 1;
            } else {
                flag = 0;
            }
        }
    },
    // 点击协议跳转
    clickAgreement: function () {
        wx.navigateTo({
            url: '/pages/agreement/agreement'
        })
    },
    // 首先取得checkbox 是否选中，即用户选择的是免押租借，还是押金租借
    depositChange: function (e) {
        var isfree = "";
        if (e.detail.value == '') {
            isfree = 0
        } else {
            isfree = 1
        }
        this.setData({
            isfree: isfree
        });
    },
    // ==================== 免押租借 =======================
    clickBorrowBut() {
        let openid = app.globalData.openID;
        if (openid != 'miand') {
            let isfree = this.data.isfree;
            if (isfree == 1) {
                // 微信免押租借
                this.startFreeBorrow();
            } else {
                // 未选择免押租借（未同意协议，则走押金租借）
                this.startBorrow();
            }
        } else {
            wx.showModal({
                title: '温馨提示',
                content: 'Hi~请确认登录，登录即可享受充电服务',
                success: function (sm) {
                    if (sm.confirm) {
                        // 未授权，跳转到授权页面
                        wx.navigateTo({
                            url: '../authorization/authorization?scene=2'
                        });
                    } else if (sm.cancel) {
                        wx.showToast({
                            title: "您点击了取消",
                            icon: 'none',
                            duration: 2000
                        });
                    }
                }
            })
        }
    },
    // ====================== 押金租借 ========================
    startBorrow() {
        let openid = app.globalData.openID;
        if (openid == 'miand') {
            wx.showModal({
                title: '温馨提示',
                content: 'Hi~请确认登录，登录即可享受充电服务',
                success: function (sm) {
                    if (sm.confirm) {
                        // 未授权，跳转到授权页面
                        wx.navigateTo({
                            url: '../authorization/authorization?scene=2'
                        });
                    } else if (sm.cancel) {
                        wx.showToast({
                            title: "您点击了取消",
                            icon: 'none',
                            duration: 2000
                        });
                    }
                }
            });
            return;
        }
        let that = this;
        if (that.data.isClick) {
            wx.showLoading({
                title: '请稍后...',
                mask: true
            });
            that.setData({
                isClick: false
            });
            utils.httpRequest('/deviceBorrow', {
                sn: that.data.info.sn,
                freeDeposit: 0
            }, function (res) {
                switch (res.code) {
                    case 1://开始租借
                        wx.hideLoading();
                        wx.navigateTo({
                            url: '../onLoan/onLoan?data=' + JSON.stringify(res.data)
                        });
                        break;
                    case 3://余额不足
                        wx.showLoading({
                            title: '请稍后...',
                            mask: true
                        });
                        utils.wxPayPayment(res.data.amount, 1, res.data.sn, 0, function (order_id) {
                            wx.hideLoading();
                            // 查询用户是否支付
                            if (order_id != null) {
                                that.checkOrderStatus(order_id);
                            } else {
                                that.setData({
                                    isClick: true
                                });
                            }
                        }, function () {
                            that.setData({
                                isClick: true
                            });
                            wx.hideLoading();
                        });
                        break;
                    case 4: // 存在未支付的金额
                        wx.hideLoading();
                        wx.showModal({
                            title: '温馨提示',
                            content: res.msg,
                            confirmText: "马上查看",
                            success(result) {
                                if (result.confirm) {
                                    // 用户点击了确认，跳转到要支付的页面, 押金补足支付
                                    wx.navigateTo({
                                        url: '../payMoney/payMoney?used_id=' + res.data.used_id
                                    });
                                } else {
                                    wx.showToast({
                                        title: "您点击了取消",
                                        icon: 'none',
                                        duration: 2000
                                    });
                                    that.setData({
                                        isClick: true
                                    });
                                }
                            }
                        });
                        break;
                    default:
                        that.setData({
                            isClick: true
                        });
                        wx.hideLoading();
                        break;
                }
            }, function () {
                that.setData({
                    isClick: true
                })
                wx.hideLoading();
            })
        }
    },
    // ========================== 微信免押租借 ============================
    startFreeBorrow() {
        let that = this;
        let wxfree_isClick = app.globalData.wxfree_isClick;
        if (that.data.isClick && wxfree_isClick) {
            wx.showLoading({
                title: 'loading...',
                mask: true
            })
            that.setData({
                isClick: false
            })
            let used_id = that.data.used_id;
            utils.httpRequest('/deviceBorrow', {
                sn: that.data.info.sn,
                freeDeposit: 1,
                used_id: used_id
            }, function (res) {
                switch (res.code) {
                    case 3:
                        // 发起创建微信分订单请求
                        utils.wxPayFreeze(res.data.amount, res.data.sn, function (used_id) {
                            that.setData({
                                isClick: true,
                                used_id: ""
                            });
                            wx.hideLoading();
                        }, function () {
                            that.setData({
                                isClick: true
                            });
                            wx.hideLoading();
                        });
                        break;
                    default:
                        that.setData({
                            isClick: true
                        });
                        wx.hideLoading();
                        break;
                }
            }, function () {
                that.setData({
                    isClick: true
                })
                wx.hideLoading();
            })

        }
    },

    // ================== 校验用户用户是否支付成功（微信分确认不在这里进行判断） ===================
    checkOrderStatus: function (order_id) {
        let that = this;
        let check = that.data.checkNum;
        check++;
        that.setData({
            checkNum: check
        });
        if (that.data.checkNum < 25) {
            utils.httpRequest('/checkOrderStatus', {
                order_id: order_id,
            }, function (res) {
                if (res.data.status == 1) {
                    that.setData({
                        isClick: true
                    });
                    clearInterval(that.data.check_timer);
                    wx.hideLoading();
                    that.startBorrow();
                } else {
                    // setTimeout(() => {
                    //     that.checkOrderStatus(order_id);
                    // }, 3000)
                    clearInterval(that.data.check_timer);
                    //执行定时器任务
                    var timerTem = setTimeout(() => {
                        that.checkOrderStatus(order_id);
                    }, 1500);
                    that.setData({
                        check_timer: timerTem
                    });
                }
            }, function () {
                wx.hideLoading();
            })
        } else {
            wx.hideLoading();
            wx.showToast({
                title: "订单异常,请联系客服",
                icon: 'none',
                duration: 2000
            });
        }
    },
    onHide: function () {
        let e = this;
        this.setData({
            checkNum: 0,
            isClick: true,
        });
        clearInterval(e.data.check_timer);
    },
    onUnload: function () {
        let e = this;
        this.setData({
            checkNum: 0,
            isClick: true,
        });
        clearInterval(e.data.check_timer);
    },
    // ================== 授权手机号 ===================
    getPhoneNumber(e) {
        var errMsg = e.detail.errMsg;
        var iv = e.detail.iv;
        var encryptedData = e.detail.encryptedData;
        let that = this;
        if (errMsg == "getPhoneNumber:fail:user deny") {
            // 用户拒绝
            let refuseShow = that.data.refuse_show;
            let refuseAfterToBorrow = that.data.refuse_after_borrow;
            // console.log("refuseShow --> " + refuseShow);
            if (refuseShow == 1) {
                wx.showModal({
                    title: '温馨提示',
                    content: that.data.refuse_msg,
                    showCancel: false,
                    confirmText: '确认',
                    success: function (res) {
                        if (res.confirm) {
                            if (refuseAfterToBorrow == 1) {
                                that.setData({
                                    need_tel: 0
                                });
                            }
                        }
                    }
                })
            } else {
                if (refuseAfterToBorrow == 1) {
                    that.setData({
                        need_tel: 0
                    });
                }
            }
        } else {
            wx.login({
                success(res) {
                    if (res.code) {
                        utils.httpRequest('/login', {
                            code: res.code
                        }, function (res) {
                            // 用户允许授权
                            utils.httpRequest('/getPhoneNumber', {
                                "iv": iv,
                                "encryptedData": encryptedData
                            }, function (res) {
                                if (res.code == 1) {
                                    wx.showToast({
                                        title: "授权成功",
                                        icon: 'none',
                                        duration: 2000
                                    });
                                }
                            });
                        })
                    }
                }
            });
            // 不管是否授权成功，只要用户点击了授权，则设置成功
            that.setData({
                need_tel: 0
            });
        }
    }
});